package lex.explorer.directory_on_catalog_model;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.filechooser.FileSystemView;

public class FileNode extends LazyMutableTreeNode implements Comparable<FileNode>
{
	private static FileNode[] EMPTY_ARRAY = new FileNode[0];
	private static FileSystemView fsv = FileSystemView.getFileSystemView();

	public FileNode( File file )
	{
		super( file );
	}


	public boolean isLeaf()
	{
		if( false == hasLoaded() )
		{
			return false;
		}
		else
		{
			return super.isLeaf();
		}
	}

	protected void loadChildren()
	{
		FileNode[] nodes = getChildren();
		for( FileNode node : nodes )
			this.add( node );
	}

	private FileNode[] getChildren()
	{
//		File[] files = fsv.getFiles( getFile(), false );
		File[] files = this.getFile().listFiles();
		if( null == files || 0 == files.length )
			return EMPTY_ARRAY;
		//===============================
		ArrayList<FileNode> nodes = new ArrayList<FileNode>();
		// keep only directories, no "file" in the tree.
		for( File file : files )
			if( true == file.isDirectory() )
				nodes.add( new FileNode( file ) );
		// sort directories, FileTreeNode implements Comparable
		FileNode[] result = nodes.toArray( EMPTY_ARRAY );
		Arrays.sort( result );
		return result;
	}

	public File getFile()
	{
		return (File) getUserObject();
	}

	public String toString()
	{
		return fsv.getSystemDisplayName( this.getFile() );
	}

	public int compareTo( FileNode o )
	{
		return getFile().compareTo( o.getFile() );
	}
}
